/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao;

import exception.DuplicateConstraintException;
import exception.RemoveConstraintException;
import java.util.List;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.validation.ConstraintViolationException;
import model.entidades.Motivo;

/**
 *
 * @author helton
 */
public class MotivoDao {
    
    @PersistenceContext
    private EntityManager em;

    public void insert(Motivo motivo) throws DuplicateConstraintException {
        try {
            em.persist(motivo);
            em.flush();
        } catch (Exception e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                throw new DuplicateConstraintException("Descrição", motivo.getDescricao());
            }
        }
    }

    public Motivo update(Motivo motivo) throws DuplicateConstraintException {
        try {
            motivo = em.merge(motivo);
            em.flush();
        } catch (Exception e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                throw new DuplicateConstraintException("Descrição", motivo.getDescricao());
            }
        }
        return motivo;
    }

    public void delete(Motivo motivo) throws RemoveConstraintException {
        try {
            motivo = em.merge(motivo);
            em.remove(motivo);
            em.flush();
        } catch (Exception e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                throw new RemoveConstraintException();
            }
        }
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public Motivo findById(Object id) {
        return em.find(Motivo.class, id);
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public List<Motivo> getAll() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Motivo> cq = cb.createQuery(Motivo.class);
        Root<Motivo> motivos = cq.from(Motivo.class);
        cq.select(motivos);
        return em.createQuery(cq).getResultList();
    }
}
